package org.aug.demo.jvm.classpath.impl;

import org.aug.demo.jvm.classpath.Entry;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//CompositeEntry 表示以文件分隔符（如 ;）分割的多个路径。
// 它实际上可以分割成更小的 Entry 去处理，Entry 接口中的静态方法正好可以直接判断各个路径该如何创建 Entry。
public class CompositeEntry implements Entry {
    private final List<Entry> entryList = new ArrayList<>();

    public CompositeEntry(String pathList){
        String[] paths = pathList.split(File.pathSeparator);
        for (String path : paths) {
            entryList.add(Entry.create(path));
        }
    }

    //遍历 entryList 逐个读取；
    @Override
    public byte[] readClass(String className) throws IOException {
        for (Entry entry : entryList) {
            try{
                return entry.readClass(className);
            }catch (Exception ignored){
                //ignored
            }
        }
        throw new IOException("class not found" + className);
    }

    @Override
    public String toString(){
        String[] strs = new String[entryList.size()];
        for (int i = 0; i < entryList.size(); i++) {
            strs[i] = entryList.get(i).toString();
        }
        return String.join(File.pathSeparator,strs);
    }


}
